#pragma once

#include <iostream>
#include <string>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <strings.h>
#include <unistd.h>
#include <memory>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <functional>

#include <sys/wait.h>

#include "Log.hpp"
#include "InetAddr.hpp"

// 模板方法  模式:采用多态的方式，把固定的模板方法，用类封装
// 想要把Tcp服务中初始化服务器的过程松耦合，在外部执行一句初始化Tcp即可。

namespace Space_Socket
{
    static const int backlog = 16;
    class Socket;
    class TcpSocket;
    using sock_ptr = std::shared_ptr<Socket>;

    enum
    {
        SOCKET_ERROR = 1,
        BIND_ERROR,
        LISTEN_ERROR,   
        USAGE_ERROR
    };
    //std::unique_ptr<Socket> server = std::make_unique<TcpSocket>();
    
    class Socket
    {
    public:
        virtual void CreateSocketOrDie() = 0;
        virtual void BindSocketOrDie(InetAddr &addr) = 0;
        virtual void ListenSocketOrDie() = 0;
        virtual sock_ptr AcceptSocketOrDie(InetAddr *addr) = 0;
        virtual bool Connetor(InetAddr &addr) = 0;
        virtual void SocketReUse() = 0;
        virtual int GetSockfd() =0;
        virtual int Recv(std::string*)=0;
        virtual int Send(const std::string&)=0;
        virtual void Close()=0;

    public:
        void BuildTcpServerSocket(InetAddr &addr)
        {
            CreateSocketOrDie();
            SocketReUse();
            BindSocketOrDie(addr);
            ListenSocketOrDie();
        }
        bool BuildTcpClientSocket(InetAddr &addr)
        {
            CreateSocketOrDie();
            return Connetor(addr);
        }

        void BuidlUdpServerSocket()
        {
        }
    };

    // Tcp服务中出现的一个套接字对应一个TcpSocket类
    class TcpSocket : public Socket
    {

    public:
        TcpSocket(int sock = -1):_sockfd(sock)
        {}
        void CreateSocketOrDie() override
        {
            // 1.创建套接字文件描述符
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(FATAL, "socket create error,errno:%d:%s\n", errno, strerror(errno));
                exit(SOCKET_ERROR);
            }
            LOG(INFO, "socker create success,sockfd:%d\n", _sockfd);
        }
        void BindSocketOrDie(InetAddr &addr) override
        {
            // 2.创建套接字
            struct sockaddr_in local;

            bzero(&local, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(addr.Port());
            local.sin_addr.s_addr = inet_addr(addr.Ip().c_str());
            // 3.绑定
            int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
            if (n < 0)
            {
                LOG(FATAL, "bind errror,errno:%d:%s\n", errno, strerror(errno));
                exit(BIND_ERROR);
            }
            LOG(INFO, "bind success,socket:%d\n",_sockfd);
        }
        void ListenSocketOrDie() override
        {
            int n = ::listen(_sockfd, backlog);
            if (n < 0)
            {
                LOG(FATAL, "listen errror,errno:%d:%s\n", errno, strerror(errno));
                exit(LISTEN_ERROR);
            }
            LOG(INFO, "listen success\n");
        }
        sock_ptr AcceptSocketOrDie(InetAddr *addr) override // addr是输出型参数
        {
            struct sockaddr_in peer; // 可能会给服务器发消息的远端套接字
            socklen_t len = sizeof(peer);
            int sockfd = ::accept(_sockfd, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept errror,errno:%d:%s\n", errno, strerror(errno));
                return nullptr;
            }
            LOG(INFO, "accept success\n");

            *addr = peer;//客户端地址
            sock_ptr sp = std::make_shared<TcpSocket>(sockfd);

            return sp;
        }
        bool Connetor(InetAddr &addr) override
        {
            struct sockaddr_in server;
            socklen_t len = sizeof(server);
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(addr.Port());
            server.sin_addr.s_addr = inet_addr(addr.Ip().c_str());
            int n = ::connect(_sockfd, (struct sockaddr *)&server, len);
            if (n < 0)
            {
                LOG(FATAL, "connect server error,errno:%d:%s\n", errno, strerror(errno));
                return false;
            }
            return true;
        }
        int GetSockfd() override
        {
            return _sockfd;
        }
        int Recv(std::string* out) override
        {
            char inbuffer[4096];
            ssize_t n = recv(_sockfd,inbuffer,sizeof(inbuffer)-1,0);
            if(n > 0)
            {
                inbuffer[n] =0;
                *out += inbuffer;
            }
            return n;
        }
        int Send(const std::string& in) override
        {
            int n = ::send(_sockfd,in.c_str(),in.size(),0);
            return n;
        }
        void Close() override
        {
            if(_sockfd>-1)
                ::close(_sockfd);
        }
        void SocketReUse() override
        {
            int opt = 1;
            ::setsockopt(_sockfd,SOL_SOCKET,SO_REUSEADDR|SO_REUSEPORT,&opt,sizeof(opt));
        }
        ~TcpSocket()
        {
        }
    private:
        int _sockfd;
    };

}
